import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:magic_car/res/resources.dart';
import 'package:magic_car/user/answers.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/config.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:cached_network_image/cached_network_image.dart';

class AnswerdeailPage extends StatefulWidget {
  //final String title;
  final String aid;
  AnswerdeailPage(this.aid);

  @override
  _MyHomePageState createState() => new _MyHomePageState(aid);
}

class _MyHomePageState extends State<AnswerdeailPage> {
  final String aid;
  ScrollController _controller = new ScrollController();
  _MyHomePageState(this.aid);
  List formList;
  int page = 1;
  var ansinfo;
  bool nomoredata = false;
  bool dataloaded = false;
  initState() {
    super.initState();
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        print('滑动到了最底部');
        loadAns();
      }
    });

    formList = [];
    loadinfo();
    loadAns();
  }

  Widget buildImgs() {
    List<Widget> tiles = [];

    Widget content;

    List items = ansinfo["image_url"];
    
    for (var i = 0; i < items.length; i++) {
      //List temp1 = items[i] as List;
      if(items[i]!=null && items[i].length>0){
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(5, 0, 0, 10),
        child: GestureDetector(
            onTap: () {
              print('点击查看图片');
              Navigator.of(context).push(
                NinePicture(items, i),
              );
            },
            child: Image.network(
              items[i],
              width: 100,
              height: 100,
              fit: BoxFit.fill,
            )),
      ));
      }
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  loadinfo() {
    Map<String, String> map = new Map();
    map["id"] = this.aid.toString();
    print(map);
    HttpHelper.post(HttpHelper.API_GetAskDetail, (data) async {
      if (data != null) {
        print(data);
        Map temp = data["info"];
        setState(() {
          ansinfo = temp;
          dataloaded = true;
        });
      }
    }, params: map);
  }

  //加载回答
  loadAns() async {
    if (nomoredata) return;
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["id"] = this.aid.toString();
    map["page"] = page.toString();
    print(map);
    HttpHelper.post(HttpHelper.API_GetAsk, (data) async {
      if (data != null) {
        print(data);
        print(data["info"].length.toString());
        if (data["info"].length == 0) {
          //Toast.show('暂无评论', context);
        } else {
          if (page == 1) {
            setState(() {
              formList = [];
            });
          }
          if (data["code"].toString() == "1") {
            List add = data["info"];
            formList.addAll(add);
            setState(() {
              formList = formList;
            });
            if (add.length == 10) {
              page = page + 1;
              nomoredata = false;
            } else {
              nomoredata = true;
            }
            // if (page > 1) {
            //   List add = data["info"];
            //   formList.addAll(add);
            //   setState(() {
            //     formList = formList;
            //   });
            // }else{

            // setState(() {
            //   formList = data["info"];
            //   page = page + 1;
            // });
            // }
          }
        }
      }
    }, params: map);
  }

  //构建评论视图
  Widget buildcoment() {
    // child: new Container(
    //               width: 60,
    //               height: 60,
    //               child: ClipRRect(
    //                 borderRadius: BorderRadius.circular(30),
    //                 child: new Image.asset('resource/images/zhanshi/car.jpeg',
    //                     width: 50, height: 50, fit: BoxFit.cover),
    //               ))),
    List<Widget> tiles = [];
    Widget content;
    if (formList.length > 0) {
      for (var i = 0; i < formList.length; i++) {
        var item = formList[i];
        var infoStyle = TextStyle(color: Color(0xff999999), fontSize: 13);
        var littleStyle = TextStyle(color: Colors.black, fontSize: 16);

        var top = Row(
          //顶部,通过Flex布局的Row进行横向排列,Expanded中间
          children: <Widget>[
            ClipRRect(
                borderRadius: BorderRadius.circular(15.0),
                child: item['avatar'] == ""
                    ? Image.asset("resource/images/zhanshi/car.jpeg",
                        width: 30, height: 30)
                    : CachedNetworkImage(
                        fit: BoxFit.fill,
                        imageUrl: item['avatar'],
                        width: 30,
                        height: 30,
                      )),
            Expanded(
              child: Padding(
                child: Text(item["name"]),
                padding: EdgeInsets.only(left: 4),
              ),
            ),
            Text(
              item["ctime"],
              style: infoStyle,
            )
          ],
        );
        var coment = Padding(
            padding: new EdgeInsets.fromLTRB(35, 0, 10, 10),
            child: Column(
              // mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Text(
                  item["answer"],
                  style: TextStyle(
                      fontSize: 12, color: Color.fromRGBO(102, 102, 102, 1)),
                )
              ],
            ));

        var imgs = item["img"][0] != ""
            ? new Container(
                child: buildCImgs(item),
                padding: new EdgeInsets.fromLTRB(35, 0, 20, 0),
              )
            : new Container(height: 0, child: new Text(''));
        var bottom = Align(
          alignment: Alignment.centerRight,
          child: new GestureDetector(
              onTap: () {
                dianzan(item);
              },
              child:
              Padding(padding: EdgeInsets.fromLTRB(0, 0, 0, 5),child:
               Row(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Image.asset('resource/images/user/dianzan.png'),
                  Container(width: 8,),
                  Text(
                    item["haszan"].toString(),
                    style: TextStyle(
                        fontSize: 12, color: Color.fromRGBO(51, 51, 51, 1)),
                  )
                ],
              ))),
        );
        tiles.add(Container(
          margin: EdgeInsets.fromLTRB(0, 0, 0, 5),
          child:
          Container(
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  width: 1,color: Colours.base_page_color
                )
              )
            ),
            child:
           Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[top, coment, imgs, bottom],
          )),
        ));
      }
    }
    //tiles.add(button);
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    // content = tiles;
    return content;
  }

  dianzan(item) async {
    Map<String, String> map = new Map();
    SharedPreferences pref = await SharedPreferences.getInstance();
    map["uid"] = pref.getString('uid');
    map["aid"] = item["id"].toString();
    print(map);

    HttpHelper.post(HttpHelper.API_Dianzan, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);
        setState(() {
          //  ansinfo = temp;
          //  dataloaded = true;
        });
      }
    }, params: map);
  }

//评论视图里面的图片
  Widget buildCImgs(item) {
    List<Widget> tiles = [];

    Widget content;

    List items = item["img"];
    print('图片数组长度' + items.isNotEmpty.toString());
    if (items.length > 0) {
      // tiles.add(new Container(
      //       padding: new EdgeInsets.fromLTRB(60, 0, 20, 0),)
      for (var i = 0; i < items.length; i++) {
        //List temp1 = items[i] as List;
        tiles.add(new Container(
            color: Color.fromRGBO(245, 245, 245, 1),
            padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
            child: Padding(
              padding: new EdgeInsets.fromLTRB(5, 5, 0, 5),
              child: GestureDetector(
                  onTap: () {
                    print('点击查看图片');
                    Navigator.of(context).push(
                      NinePicture(items, i),
                    );
                  },
                  child: Image.network(items[i], width: 60, height: 60)),
            )));
      }
    }
    content = new Wrap(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    if (dataloaded == true) {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 15, 0, 50),
          child: Container(
              decoration: new BoxDecoration(
                color: Colors.white,
              ),
              child: Container(
                // decoration: new BoxDecoration(
                //     color: Colors.white,
                //     border: Border(
                //         bottom: BorderSide(width: 1, color: Colors.red))),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Padding(
                      padding: new EdgeInsets.fromLTRB(10, 15, 10, 5),
                      child: Column(
                        children: <Widget>[Text(ansinfo["name"])],
                      ),
                    ),
                    Padding(
                      padding: new EdgeInsets.fromLTRB(10, 5, 10, 10),
                      child: Column(
                        children: <Widget>[
                          Text(
                            ansinfo["details"],
                            style: TextStyle(
                                fontSize: 12,
                                color: Color.fromRGBO(102, 102, 102, 1)),
                          )
                        ],
                      ),
                    ),
                    Padding(
                      padding: new EdgeInsets.fromLTRB(10, 10, 10, 10),
                      child:ansinfo["image_url"].isEmpty? Container():buildImgs(),
                      // child: Row(
                      //   children: <Widget>[Text('总试题数：16')],
                      // ),
                    ),
                    Padding(
                      padding: new EdgeInsets.fromLTRB(10, 10, 20, 10),
                      child: Column(
                        children: <Widget>[
                          Align(
                              alignment: Alignment.bottomLeft,
                              child: RichText(
                                text: TextSpan(
                                    text: '全部回答',
                                    style: TextStyle(
                                        color: Color.fromRGBO(51, 51, 51, 1),
                                        fontSize: 12),
                                    children: <TextSpan>[
                                      TextSpan(
                                          text: '（' +
                                              ansinfo["answerNum"].toString() +
                                              '）',
                                          style: TextStyle(
                                              color: Color.fromRGBO(
                                                  27, 182, 251, 1)))
                                    ]),
                              ))
                        ],
                      ),
                    ),
                    Padding(
                        padding: new EdgeInsets.fromLTRB(10, 10, 20, 10),
                        child: buildcoment()),
                  ],
                ),
              ))));
    }

    content = new Column(
        children: tiles //重点在这里，因为用编辑器��Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
          titleSpacing: 0,
          title: new Text(
            '问答详情',
            style: TextStyle(fontSize: Config.title_size),
          ),
          elevation: 0,
          backgroundColor: Colors.white
          //backgroundColor: Color.fromRGBO(255, 204, 48, 1),
          ),
      body: new Center(
        child: Container(
            decoration: new BoxDecoration(
              color: Color.fromRGBO(245, 245, 245, 1),
            ),
            child:
                // new ListView(children: <Widget>[
                Stack(
              children: <Widget>[
                Align(
                    alignment: Alignment.topCenter,
                    child: new RefreshIndicator(
                      onRefresh: _onRefresh,
                      child: new ListView(
                          controller: _controller,
                          children: <Widget>[buildcontent()]),
                    )),
                Align(
                  alignment: Alignment.bottomLeft,
                  child: SizedBox(
                      width: double.infinity,
                      height: 45,
                      child: new RaisedButton.icon(
                        icon:
                            new Image.asset('resource/images/user/answer.png'),
                        label: Text(
                          '我来回答',
                          style: TextStyle(fontSize: 15),
                        ),
                        color: Color.fromRGBO(278, 182, 251, 1),
                        textColor: Colors.white,
                        onPressed: () {
                          Navigator.of(context)
                              .push(new MaterialPageRoute(builder: (_) {
                            return new UpAnsPage(ansinfo["id"].toString());
                          }));
                        },
                      )),
                )
              ],
            )
            // buildcontent()
            //]
            ),
      ),
    );
  }

  Future<Null> _onRefresh() async {
    await Future.delayed(Duration(seconds: 3), () {
      print('refresh');
      setState(() {
        page = 1;
      });
      loadAns();
    });
  }
}

class NinePicture<T> extends PopupRoute<T> {
  final String barrierLabel;
  final List picList;
  final int index;
  int startX;
  int endX;

  NinePicture(this.picList, this.index, {this.barrierLabel});

  @override
  Duration get transitionDuration => Duration(milliseconds: 2000);

  @override
  @override
  Color get barrierColor => Colors.black54;

  @override
  bool get barrierDismissible => true;

  AnimationController _animationController;

  @override
  AnimationController createAnimationController() {
    assert(_animationController == null);
    _animationController =
        BottomSheet.createAnimationController(navigator.overlay);
    return _animationController;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GestureDetector(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) => GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: _PictureWidget(picList, index),
          ),
        ),
      ),
    );
  }
}

class _PictureWidget extends StatefulWidget {
  final List picList;
  final int index;

  _PictureWidget(this.picList, this.index);

  @override
  State createState() {
    return _PictureWidgetState();
  }
}

class _PictureWidgetState extends State<_PictureWidget> {
  int startX = 0;
  int endX = 0;
  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    index = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Colors.transparent,
      child: new Container(
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            GestureDetector(
              child: Center(
                child: CachedNetworkImage(
                  imageUrl: widget.picList[index],
                  fit: BoxFit.fill,
                ),
              ),
              onHorizontalDragDown: (detail) {
                startX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragUpdate: (detail) {
                endX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragEnd: (detail) {
                _getIndex(endX - startX);
                setState(() {});
              },
              onHorizontalDragCancel: () {},
            ),
            Align(
                alignment: Alignment.bottomCenter,
                child: Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 20),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: List.generate(
                      widget.picList.length,
                      (i) => GestureDetector(
                        child: CircleAvatar(
                          foregroundColor: Theme.of(context).primaryColor,
                          radius: 5.0,
                          backgroundColor: index == i
                              ? Theme.of(context).primaryColor
                              : Colors.white,
                        ),
                        onTap: () {
                          setState(() {
                            startX = endX = 0;
                            index = i;
                          });
                        },
                      ),
                    ).toList(),
                  ),
                ))
          ],
        ),
        alignment: Alignment.center,
      ),
    );
  }

  void _getIndex(int delta) {
    if (delta > 50) {
      setState(() {
        index--;
        index = index.clamp(0, widget.picList.length - 1);
      });
    } else if (delta < 50) {
      setState(() {
        index++;
        index = index.clamp(0, widget.picList.length - 1);
      });
    }
  }
}
